/* ** por compatibilidad se omiten tildes **
================================================================================
 TRABAJO PRACTICO 3 - System Programming - ORGANIZACION DE COMPUTADOR II - FCEN
================================================================================
  definicion de estructuras para administrar tareas
*/

#include "tss.h"
#include "mmu.h"
tss tss_inicial;
tss tss_idle;

void tss_inicializar() {
	/*Tarea inicial*/
	unsigned int inicial = (unsigned int) &tss_inicial;
	gdt[13].base_0_15 = (unsigned short) inicial;
	gdt[13].base_23_16 = (unsigned char) (inicial>>16);
	gdt[13].base_31_24 = (unsigned char) (inicial>>24);
}

void tss_inicializar_idle(){
	unsigned int idle = (unsigned int) &tss_idle;
	gdt[14].base_0_15 = (unsigned short) idle;
	gdt[14].base_23_16 = (unsigned char) (idle>>16);
	gdt[14].base_31_24 = (unsigned char) (idle>>24);
	tss_idle.eip = 0x16000;
	tss_idle.esp = 0x27000;
	tss_idle.ebp = 0x27000;
	tss_idle.cr3 = 0x27000;
	tss_idle.eflags = 0x202;
	tss_idle.es = 0x50;
	tss_idle.cs = 0x40;
	tss_idle.ss = 0x50;
	tss_idle.ds = 0x50;
	tss_idle.fs = 0x60;
	tss_idle.gs = 0x50;
}

void completar_tss_zombie(tss* libre, char tipo, char jugador, unsigned int pos_i,int slot){
	libre->cr3 = (unsigned int) mmu_inicializar_dir_zombi(jugador,pos_i,tipo);
	libre->	eip = 0x8000000;
	libre->esp = 0x8001000;
	libre->ebp = 0x8001000;
	libre->eflags = 0x202;
	//Código nivel usuario:  {index = 9, ti = 0, rpl = 3}  01001 0 11 = 0100 1011 = 4b
	//Datos nivel usuario: 	{index = 11, ti = 0, rpl = 3}  01011 0 11 = 0101 1011 = 5b 
	libre->eax = 0;
	libre->ebx = 0;
	libre->ecx = 0;
	libre->edx = 0;
	libre->unused0 = 0;
	libre->unused1 = 0;
	libre->unused2 = 0;
	libre->unused3 = 0;
	libre->unused4 = 0;
	libre->unused5 = 0;
	libre->unused6 = 0;
	libre->unused7 = 0;
	libre->unused8 = 0;
	libre->unused9 = 0;
	libre->unused10 = 0;
	libre->esi = 0;
	libre->edi = 0;
	libre->ss0 = 0x50;
	libre->cs = 0x4b;
	libre->es = 0x5b;
	libre->ss = 0x5b;
	libre->ds = 0x5b;
	libre->fs = 0x5b;
	libre->gs = 0x5b;
	libre->esp0 = (unsigned int) dame_pagina_libre();
	if(jugador == 'A'){
		unsigned int primerA = (unsigned int)&tss_zombisA[slot];
		gdt[slot+15].base_0_15 = (unsigned short) primerA;
		gdt[slot+15].base_23_16 = (unsigned char) primerA>>16;
		gdt[slot+15].base_31_24 = (unsigned char) primerA>>24;
	}
	else{
		unsigned int primerB = (unsigned int)&tss_zombisB[slot];
		gdt[slot+23].base_0_15 = (unsigned short) primerB;
		gdt[slot+23].base_23_16 = (unsigned char) primerB>>16;
		gdt[slot+23].base_31_24 = (unsigned char) primerB>>24;
	}
}